/*************************************************************************
 > File Name   : rbac_user_dao.js
 > Author      : zhoutk
 > Mail        : zhoutk@189.cn
 > Created Time: 2015/5/13 23:26
 ************************************************************************/
var dbconn = require("dbconn");
var table = "rbac_user";
var crypto = require('crypto');

function rbac_user_dao() {
    //获取列表
    this.list = function (id, params, callback) {
        var page = params['page'] != null ? params['page'] : 1;
        var size = params['size'] != null ? params['size'] : 9999;
        var sql = dbconn.buildQuerySql(table, params);
        dbconn.queryPage(sql, null, page, size, callback);
    };

    //获取单个用户
    this.retrieve = function (id, params, callback) {
        dbconn.getObject(table, {id: id}, callback);
    };

    //创建用户
    this.create = function (id, params, callback) {
        if(params["password"].length < 3){
            callback({"outcome": 0, "error": "密码长度必须不小于三个字符！"});
        }
        else{
            getUserByName(params["account"], function (user) {
                if (user != null) {
                    callback({"outcome": 0, "error": "用户名已经存在，请另选其它的合法用户名！"});
                }
                else {
                    getUserByEmail(params["email"], function (user) {
                        if (user != null) {
                            callback({"outcome": 0, "error": "Email已经存在，请另选其它的Email！"});
                        }
                        else {
                            params["password"] = crypto.createHash('md5').update(params["password"]).digest('hex');
                            dbconn.addObject(table, params, callback);
                            callback({"outcome": 1, "info": "新用户创建成功！"});
                        }
                    });
                }
            });
        }
    };

    //更新用户
    this.update = function (id, params, callback) {
        delete params["password"];              //忽略密码
        getUserById(id,function(user){
            if(user.account == params["account"] && user.email == params["email"]){      //用户名与Email都没有改变
                dbconn.updateObject(table, params, {id: id}, callback);
                callback({"outcome": 1, "info": "用户信息修改成功！"});
            }
            else if(user.account != params["account"] && user.email == params["email"]){
                getUserByName(params["account"],function(user){
                    if(user != null)
                        callback({"outcome": 0, "error": "用户名已经存在，请另选其它的合法用户名！"});
                    else{
                        dbconn.updateObject(table, params, {id: id}, callback);
                        callback({"outcome": 1, "info": "用户信息修改成功！"});
                    }
                });
            }
            else if(user.account == params["account"] && user.email != params["email"]){
                getUserByEmail(params["email"],function(user){
                    if(user != null)
                        callback({"outcome": 0, "error": "Email已经存在，请另选其它的Email！"});
                    else{
                        dbconn.updateObject(table, params, {id: id}, callback);
                        callback({"outcome": 1, "info": "用户信息修改成功！"});
                    }
                });
            }
            else{
                getUserByName(params["account"],function(user){
                    if(user != null)
                        callback({"outcome": 0, "error": "用户名已经存在，请另选其它的合法用户名！"});
                    else{
                        getUserByEmail(params["email"],function(user){
                            if(user != null)
                                callback({"outcome": 0, "error": "Email已经存在，请另选其它的Email！"});
                            else{
                                dbconn.updateObject(table, params, {id: id}, callback);
                                callback({"outcome": 1, "info": "用户信息修改成功！"});
                            }
                        });
                    }
                });
            }
        });
    };

    //删除用户
    this.delete = function (id, params, callback) {
        dbconn.deleteObject(table, {id: id}, callback);
    };
}

exports.dao = rbac_user_dao;

exports.modiPwd = function (req, res, callback) {
    if (req.params["password"].length < 3 ) {
        callback({"outcome": 0, "error": "密码长度必须不小于三个字符！"});
    }
    else {
        var password = crypto.createHash('md5').update(req.params["password"]).digest('hex');
        var oldPwd = crypto.createHash('md5').update(req.params["oldPwd"]).digest('hex');
        var username = req.params["account"];

        getUserByName(username, function (result) {
            if (result == null) {
                callback({"outcome": 0, "error": "用户名不存在！"});
            }
            else if (result.password.toLowerCase() != oldPwd) {
                callback({"outcome": 0, "error": "用户原密码不正确！"});
            }
            else {
                dbconn.updateObject(table, {"password":password}, {id: result.id}, callback);
                callback({"outcome": 1, "info": "用户密码修改成功！"});
            }
        });
    }
};

exports.login = function (req, res, session, callback) {
    if (req.params["password"].length < 3 || req.params["account"].length < 3) {
        callback({"outcome": 0, "error": "用户名或密码不正确！"});
    }
    else {
        var password = crypto.createHash('md5').update(req.params["password"]).digest('hex');
        var username = req.params["account"];

        getUserByName(username, function (result) {
            if (result == null) {
                callback({"outcome": 0, "error": "用户名不存在！"});
            }
            else if (result.password.toLowerCase() != password) {
                callback({"outcome": 0, "error": "用户密码不正确！"});
            }
            else {
                session.save(req.session.sid, {"username": username}, null);
                callback({"outcome": 1, "target": "index.html", "info":"用户登录成功！"});
            }
        });
    }
};

exports.loginout = function (req, res, session, callback) {
    session.save(req.session.sid, {"username": ""}, null);
    callback({"outcome": 1, "target": "index.html", "info":"用户注销成功！"});
};

function getUserByEmail(email, callback) {
    dbconn.getObject(table, {email: email}, callback);
}

function getUserById(id, callback) {
    dbconn.getObject(table, {id: id}, callback);
}

function getUserByName(name, callback) {
    dbconn.getObject(table, {account: name}, callback);
}
